package fr.vincent.aquarium.metier.commun;

import java.io.Serializable;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * DAO abstrait - Impl�mente les m�thodes CRUD
 * @param <T>
 */
public abstract class HibernateDaoSupport<T extends Serializable> implements Dao<T> {	

	@Autowired
	protected SessionFactory sessionFactory;
	
	protected Class<T> clazz;

	public void setClazz(final Class<T> clazzToSet) {
		clazz = clazzToSet;
	}

	@Override
	public void save(T entity) {
		this.getCurrentSession().saveOrUpdate(entity);
	}

	@Override
	public void update(T entity) {
		this.getCurrentSession().update(entity);
	}

	@Override
	public void delete(T entity) {
		this.getCurrentSession().delete(entity);
	}

	@SuppressWarnings("unchecked")
	@Override
	public T get(long id) {
		return (T) this.getCurrentSession().get(this.clazz, id);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<T> get() {
		return this.getCurrentSession()
				.createQuery("from " + this.clazz.getName()).list();
	}

	@Override
	public void delete(long id) {
		this.getCurrentSession().delete(this.get(id));
	}

	@Override
	public final Session getCurrentSession() {
		Session session = null;
		
		try { 
			session = sessionFactory.getCurrentSession();
		} catch (NullPointerException | HibernateException e){
			session = sessionFactory.openSession();
		}
		
		return session;
	}
}
